package com.scm.util;

import java.sql.*;
import java.util.*;

import com.scm.dao.BaseDao;
import com.scm.page.Page;

public class PageUtil {
	
	/**
	 * 分页查询功能
	 * @param queryCondition 查询条件
	 * @param currentPage 当前页码
	 * @param daoClass dao的大Class对象
	 * 该类包含int selectCount(Map<String, String> queryCondition) 方法，返回总条数
	 * 该类包含List<T> selectData(Map<String, String> queryCondition) 方法，返回数据
	 * @return
	 * @throws Exception
	 */
	public static <T> Page<T> selectPage(BaseDao<T> dao,int currentPage,Map<String, String> queryMap) throws SQLException{

		Page<T> page = new Page<T>();
		page.setCurrentPage(currentPage);
			
		//查询总条数
		int totalCount = dao.selectcount(queryMap);
		
		int pageCount = -1;
		if(totalCount%page.getPageSize() == 0){
			pageCount = totalCount/page.getPageSize();
		}else{
			pageCount = totalCount/page.getPageSize()+1;
		}
		page.setPageCount(pageCount);
		page.setTotalCount(totalCount);
		//如果当前页码大于总页数 强制跳转至第一页
		if(currentPage > pageCount){
			page.setCurrentPage(1);
		}
		
		
		queryMap.put("startNo", (page.getCurrentPage()-1)*page.getPageSize()+"");
		queryMap.put("pageSize", page.getPageSize()+"");
		
		//查询数据
		List<T> users = dao.selectData(queryMap);
		page.setDataList(users);
		
		
		return page;
	}
	
}
